package com.tiger.utils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class QRCode {
	private String content;
	private File file;
	private int width;
	private int height;

	
	public static QRCode create(String content, int width, int height) throws WriterException, IOException {
		QRCode qrCode = new QRCode();
		qrCode.content = content;
		qrCode.width = width;
		qrCode.height = height;
		qrCode.file = new File(Conf.get("static.upload.dir"), "qr" + IdGenerator.uuid() + ".jpg");
		qrCode.save();
		return qrCode;
	}
	
	
	public String getContent() {
		return content;
	}


	public File getFile() {
		return file;
	}


	public int getWidth() {
		return width;
	}


	public int getHeight() {
		return height;
	}


	@Override
	public String toString() {
		return "QRCode [content=" + content + ", file=" + file + ", width=" + width + ", height=" + height + "]";
	}


	private void save() throws WriterException, IOException {
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map<EncodeHintType,Object> hints = new HashMap<>();
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		MatrixToImageWriter.writeToPath(bitMatrix, "jpg", file.toPath());
	}
	
}
